import smap.archiver.client
import time
import scipy.interpolate
import csv
import calendar

#change the name and location of the output file
f1 = open('/home/cbe/.gvfs/bsg on 169.229.130.74/New York Times/Analysis/interpTest.csv', 'wb')
testsout = csv.writer(f1,dialect='excel') 

#input stream ids
c = smap.archiver.client.SmapClient(base='http://new.openbms.org/backend', key='SA2nYWuHrJxmPNK96pdLKhnSSYQSPdALkvnA', private=True)

#insert utc times
start_time = int(calendar.timegm(time.strptime('2012-04-06 00:00:00', '%Y-%m-%d %H:%M:%S')))
end_time = int(calendar.timegm(time.strptime('2012-04-07 00:00:00', '%Y-%m-%d %H:%M:%S')))
print start_time  
new_time = []
interpolated = []
interval = 30 #number of seconds for interval
x = start_time + interval
while x < end_time-interval: #shrink total time interval by one interval length on each side to account for missing data
    x = x + interval 
    new_time.append(x*1000)
newdata = c.data('Path = \'/cbemtg/m6/c1\' or Path = \'/cbemtg/m7/c1\'',start_time, end_time)
#diag = c.query('select distinct uuid where Metadata/Extra/DeviceName = \'Plenum temp\'')
#print diag
#print newdata

for row in newdata[1]:
    if len(row[:,0]) > 0:
        f_data = scipy.interpolate.interp1d(row[:,0], row[:,1], bounds_error=False)  
        interpolated.append(f_data(new_time))
    #else:
        #interpolated.append('no_data')
transposed = zip(*interpolated)
#rint int(maxi)

grid = []
names = []
row = ['uuids']
for x in xrange(len(newdata[0])):
    uuid = newdata[0][x]
    if len(newdata[1][x][:,0]) > 0:
        grid.append(c.query('select distinct Metadata/Extra/GridLocation where uuid = \'%s\'' % uuid))
        names.append(c.query('select distinct Metadata/Extra/DeviceName where uuid = \'%s\'' % uuid) + c.query('select distinct Metadata/Extra/SensorLocation where uuid = \'%s\'' % uuid))
        #names.append(c.query('select distinct Path where uuid = \'%s\'' % uuid))
        row.append(uuid)
testsout.writerow(row)
row = ['Name']
row.extend(names)
testsout.writerow(row)
row = ['GridLocation']
row.extend(grid)
testsout.writerow(row)

for x in xrange(len(transposed)):
    #if new_time[x]/1000 < 1320523200:
    row = [time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime((new_time[x]/1000)-(3600*7)))]
    #else:
    #    row = [time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime((new_time[x]/1000)-(3600*5)))]
    row.extend(transposed[x])
    testsout.writerow(row)

f1.close()

